package com.navi.loaddata.loadService.impl.baseData;

import com.navi.loaddata.core.errorLog.ErrorCode;
import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.gpEntity.MArrayParamD;
import com.navi.loaddata.core.gpEntity.MOpeD;
import com.navi.loaddata.core.gpEntity.MParamD;
import com.navi.loaddata.core.mesEntity.MesProducthistory;
import com.navi.loaddata.core.mesEntity.MesProductspec;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.oracleEntity.EtlProductV;
import com.navi.loaddata.core.oracleEntity.EtlStepV;
import com.navi.loaddata.core.repository.impl.GreenPlumRepositoryImpl;
import com.navi.loaddata.core.repository.impl.MesRepositoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.navi.loaddata.core.constant.GenericDef.OTHER;
import static com.navi.loaddata.core.constant.GenericDef.SHOP_OC;

@Service
@Transactional(transactionManager = "mesPlatformTransactionManager",
        rollbackFor = {RuntimeException.class, Exception.class})
public class LoadMesBaseDataService {

    @Autowired
    private MesRepositoryImpl daomes;
    @Autowired
    private GreenPlumRepositoryImpl dao2;
    @Autowired
    private ProcessBaseDataService processBaseDataService;
    private static final Logger logger = LoggerFactory.getLogger(LoadMesBaseDataService.class);

    //STEP
    public List<EtlStepV> loadAllFinalStep(String shopId) throws Exception {
        List<EtlStepV> etlStepV = new ArrayList<>();
        List<MOpeD> stepList=new ArrayList<>();
        String hql = "from MOpeD where ope_id is not null and ope_id <>'' and shopId='" + shopId + "'";

        try {
            stepList = dao2.find(MOpeD.class, hql);
        }catch (Exception e){
            throw new ETLException2(ErrorCode.ERROR_GET_GP_STEP,e);
        }
        try {
            etlStepV = processBaseDataService.processStep(stepList);
        }catch (Exception e){
            throw new ETLException2(ErrorCode.ERROR_PROCESS_GP2ORA_STEP,e);
        }
        return etlStepV;
    }


    //PRODUCT
    public List<EtlProductV> loadAllFinalProduct(String shopId) throws Exception {
        List<MesProductspec> mesProductspecList = new ArrayList<>();
        List<EtlProductV> etlProductVList = new ArrayList<>();
        Map<String, Boolean> productMap = new HashMap<>();

        String hql = "from MesProductspec where PRODUCTIONTYPE IN ('Engineer','Production') ";
        if (!StringUtils.isEmpty(shopId)) {
            hql += " and subfactoryname = '" + shopId + "'";
        }
        try {
            mesProductspecList = daomes.find(MesProductspec.class, hql);
        }catch (Exception e){
            throw new ETLException2(ErrorCode.ERROR_GET_GP_PRODUCT,e);
        }

        try {
            mesProductspecList.forEach(p -> {
                String productName = p.getProductspecname();
                if (null == productMap.get(productName)) {
                    productMap.put(productName, true);

                    EtlProductV etlProductV = new EtlProductV();
                    etlProductV.setProductId(p.getProductspecname());
                    etlProductV.setProductVersion("00001");
                    String productGroup = OTHER;
                    if (SHOP_OC.equals(p.getSubfactoryname()) &&
                            p.getProductspecname().length() > 4) {
                        if ("L".equals(p.getProductspecname().substring(0, 1))) {
                            productGroup = p.getProductspecname().substring(2, 7);
                        } else {
                            productGroup = p.getProductspecname().substring(1, 6);
                        }
                    } else {
                        productGroup = p.getProductspecname().substring(2, 7);
                    }
                    etlProductV.setProductGroup(productGroup);
                    etlProductV.setModelName(productGroup);
                    etlProductV.setPanelSize(productGroup.substring(0, 3));
                    etlProductV.setProductType(p.getProductiontype());
                    etlProductV.setPanelQty(p.getProductquantity());
                    etlProductV.setProductIdErp(p.getErpproductspecname());

                    etlProductVList.add(etlProductV);
                }
            });
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_PROCESS_GP2ORA_PRODUCT ,e);
        }
        return etlProductVList;
    }


    public List<MesProducthistory> loadCommonGlassInfo(EtlConfDModel etlConfD, String glassId) {
        List<MesProducthistory> mesProducthistoryEntity = new ArrayList<>();
        try {
            StringBuffer hql = new StringBuffer();
            hql.append("FROM MesProducthistory WHERE subfactoryname='").append(etlConfD.getShop()).append("' ")
                    .append(" and PRODUCTNAME ='").append(glassId).append("' AND ROWNUM=1 ORDER BY TIMEKEY DESC");//取最新一笔，因为产品可能有变化
            List<MesProducthistory> allCmn = new ArrayList<>();
            allCmn=daomes.list(MesProducthistory.class, hql.toString());
            if (allCmn.size() == 0) {
                throw new ETLException2(ErrorCode.ERROR_GET_MES_HIS_CMN_GLASS,null);
            }
            mesProducthistoryEntity.add(allCmn.get(0));
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_GET_MES_HIS_CMN_GLASS,e);
        }
        return mesProducthistoryEntity;
    }

    public List<MParamD> loadParamInfo2(String shopId) {
        List<MParamD> mParamDList=new ArrayList<>();
        try {
            StringBuffer hql = new StringBuffer();
            hql.append("FROM MParamD where shopName='").append(shopId).append("' ");
            List<MParamD> mParamDS = dao2.list(MParamD.class, hql.toString());
            for(MParamD m:mParamDS){
                mParamDList.add(m);
            }
        }catch (Exception e){
            throw new ETLException2(ErrorCode.ERROR_GET_GP_PARAM,e);
        }
        return mParamDList;
    }

    public List<MArrayParamD> loadParamInfo(String shopId) {
        StringBuffer hql = new StringBuffer();
        hql.append("FROM MParamD where shopName='").append(shopId).append("' ");
        List<MParamD> mParamDS = dao2.list(MParamD.class, hql.toString());

        List<MArrayParamD> mArrayParamDList = new ArrayList<>();
        mParamDS.forEach(m -> {
            MArrayParamD mArrayParamD = new MArrayParamD();
            BeanUtils.copyProperties(m, mArrayParamD);
            mArrayParamDList.add(mArrayParamD);
        });
        return mArrayParamDList;
    }
}
